import { events }  from '../../utils/events.js';
import { ref } from 'vue';
export const editListDragHandle = (contentRef, data) => {
    let currentComponent = null; // 当前正在拖拽的模板
    let index;
    const focusIndex = ref(null);
    // 元素的开始拖拽事件
    const dragstart = (e, component, componentIndex) => {
        contentRef.value.addEventListener('dragenter', dragenter)
        contentRef.value.addEventListener('dragover', dragover)
        contentRef.value.addEventListener('dragleave', dragleave)
        contentRef.value.addEventListener('drop', drop)
        currentComponent = component;
        focusIndex.value = componentIndex;
        events.emit('start'); // 发布start事件
    }
    // 拖拽结束，清除事件
    const dragend = () => {
        contentRef.value.removeEventListener('dragenter', dragenter)
        contentRef.value.removeEventListener('dragover', dragover)
        contentRef.value.removeEventListener('dragleave', dragleave)
        contentRef.value.removeEventListener('drop', drop)
        // events.emit('end'); // 发布end事件
    }

    // dragenter 进入元素中，添加一个移动的标识
    const dragenter = (e) => {
        e.dataTransfer.dropEffect = "move";
    }
    // dragover 在目标元素中经过时，必须阻止默认行为
    const dragover = (e) => {
        e.preventDefault()
        for(let i = 0; i < data.value.length; i++) {
            if(e.clientY > data.value[i].dom.y) {
                index = i;
            }
        }
    }
    // dragleave 离开元素的时候，需要增加一个禁用标识
    const dragleave = (e) => {
        e.dataTransfer.dropEffect = "none";
    }
    const drop = (e) => {
        const item = data.value.splice(focusIndex.value, 1)
        data.value.splice(index, 0, ...item)
        events.emit('end');
    }

    const clickComponent = (item, index) => {
        data.value.forEach(item => item.focus = false)
        item.focus = true;
        focusIndex.value = index;
    }

    return {
        focusIndex,

        dragstart,
        dragend,
        clickComponent
    }
}